package logic

import (
	"context"
	"everyone/C/rpc_C/everyone"
	"everyone/C/rpc_C/internal/svc"
	"everyone/C/rpc_C/model/mysql"
	"everyone/C/rpc_C/pkg"
	"github.com/google/uuid"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *everyone.OrderCreateRequest) (*everyone.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	u := mysql.User{}
	err := u.Find(int(u.ID))
	if err != nil {
		logx.Error("未查询到此用户")
	}
	err = g.InFo(int64(g.ID))
	if err != nil {
		logx.Error("商品查询失败")
	}
	if g.ID == 0 {
		logx.Error("没有此商品")
	}
	if g.GoodsNum < 1 {
		logx.Error("商品库存不足")
	}
	orderSyn := uuid.NewString()
	o := mysql.Order{
		UserId:      in.UserId,
		GoodsId:     in.GoodsId,
		GoodsTitle:  g.GoodsTitle,
		SynOrder:    orderSyn,
		OrderStatue: 1,
		OrderType:   1,
	}
	err = o.Create()
	if err != nil {
		logx.Error("商品添加失败")
	}
	amount := strconv.FormatFloat(g.GoodsPrice, 'f', 2, 64)
	alipay := pkg.NewAlipay()
	URl := alipay.Pay(g.GoodsTitle, orderSyn, amount)
	return &everyone.OrderCreateResponse{
		OrderId: int64(o.ID),
		Url:     URl,
	}, nil
}
